package fr.xgouchet.wedding.client.presenter;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;

import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

import fr.xgouchet.wedding.client.i18n.Messages;
import fr.xgouchet.wedding.client.service.WebService;
import fr.xgouchet.wedding.shared.model.NavLink;
import fr.xgouchet.wedding.shared.model.Task;

/**
 * Presenter for the Nav Bar
 * 
 * @author x.gouchet
 * 
 */
public class NavigationPresenter implements Presenter {

	/**
	 * The display interface that the binded view needs to implement.
	 * 
	 * @author x.gouchet
	 * 
	 */
	public interface Display {

		/**
		 * Clears the data displayed
		 */
		void clearData();

		/**
		 * @param data
		 *            the string to display
		 * @param cat
		 *            the category
		 * @param token
		 *            the token
		 */
		void addData(String data, String cat, String token);

		/**
		 * @param msg
		 *            a message to display with the nav bar
		 */
		void setMessage(String msg);

		/**
		 * @param cat
		 *            the category to display or give the focus to
		 */
		void setVisibleCategory(String cat);

		/**
		 * @return the view as a single widget
		 */
		Widget asWidget();
	}

	/**
	 * Constructor
	 * 
	 * @param view
	 *            the view to present
	 */
	public NavigationPresenter(Display view) {
		mDisplay = view;
		bind();
	}

	/**
	 * @see Presenter#go(HasWidgets)
	 */
	public void go(final HasWidgets container) {
		container.clear();
		container.add(mDisplay.asWidget());
		fetchItemsDetails();
	}

	/**
	 * Binds the presenter with events
	 */
	private void bind() {
	}

	/**
	 * Fetch the details from the server
	 */
	private void fetchItemsDetails() {
		mLinks = WebService.getLinksDetails();
		presentData();
	}

	/**
	 * Presents the data on the display
	 */
	private void presentData() {
		mDisplay.clearData();
		Iterator<NavLink> it = mLinks.iterator();

		while (it.hasNext()) {
			NavLink link = it.next();
			mDisplay.addData(link.getText(), link.getCategory(), link
					.getToken());
			if (link.getToken().equals(History.getToken())) {
				mDisplay.setVisibleCategory(link.getCategory());
			}
		}

		mDisplay.setMessage(Messages.I18N
				.messageWeddingCounter(daysTillWedding()));
	}

	/**
	 * @return number of days until the wedding
	 */
	private int daysTillWedding() {
		long wedding = WebService.getSettings().getWeddingDate().getTime();
		long today = (new Date()).getTime();
		int days = (int) ((wedding - today) / Task.DAY_TO_MILLISECONDS);
		if (days < 0)
			return 0;
		return days;
	}

	/**
	 * The container of this app controller
	 */
	private Display mDisplay;

	/**
	 * List of links to present (key = link, value = text)
	 */
	private ArrayList<NavLink> mLinks;
}
